package menu

import (
	"context"
	"errors"
	"gorm.io/gorm"

	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"google.golang.org/grpc/codes"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateMenuLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateMenuLogic {
	return &UpdateMenuLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateMenuLogic) UpdateMenu(req *types.MenuUpdateReq) (resp *types.Empty, err error) {

	query := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityMenu{})

	// 检查专栏是否存在
	var existMenu model.CsCommunityMenu
	if err = query.Session(&gorm.Session{}).Where("id = ?", req.Id).First(&existMenu).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, e.NewGrpcErr(codes.NotFound, e.MenuNotFound)
		}
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	// 检查名称是否重复（排除自己）
	var exist int64

	if err = query.Session(&gorm.Session{}).Where("id != ?", req.Id).Where("name != ?", req.Name).Count(&exist).Error; err != nil {
		return nil, e.NewGrpcErr(codes.NotFound, e.DBError)
	}

	if err = query.Where("id = ?", req.Id).Updates(&model.CsCommunityMenu{
		Name:        req.Name,
		Description: req.Description,
	}).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	return &types.Empty{}, nil
}
